package com.open.capacity.client.filter;

//import com.huawei.saas.constants.Constants;
//import com.huawei.saas.context.TenantContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.Cookies;

import java.util.Base64;
import java.util.List;

/**
 * url解析
 * @program: open-capacity-platform
 * @author: GuoGaoJu
 * @create: 2023-04-03
 **/
@Slf4j
@Component
public class DomainFilter implements GlobalFilter, Ordered {

    /**
     * 将租户标识解码并放到请求头
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("请求进来……");

        ServerHttpRequest request = exchange.getRequest();

        //cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie cookie = cookies.getFirst("tenantDomain");
        String value = cookie.getValue();
        if ( value != null && (!"".equals(value)) ){



            byte[] bytes = Base64.getDecoder().decode(value);
            String tenantDomain = new String(bytes);
            log.info("租户标识："+tenantDomain);
            ServerHttpRequest newRequest = request.mutate().header("tenantDomain", tenantDomain).build();
            exchange.mutate().request(newRequest).build();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -502;
    }
}
